//
//  HousingViewController.m
//  EMMApp
//
//  Created by Mac on 16/5/17.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "HousingViewController.h"
#import "NewCustomersCell.h"


@interface HousingViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
    UITableView *_tableView;
    NSMutableDictionary *dic;//存对应的数据
    NSMutableArray *selectedArr;//二级列表是否展开状态
    NSMutableArray *titleDataArray;
    NSArray *dataArray;//数据源，显示每个cell的数据
    NSMutableDictionary *stateDic;//三级列表是否展开状态
    
    NSMutableArray *grouparr0;
    NSMutableArray *grouparr1;
    NSMutableArray *grouparr2;
    NSMutableArray *grouparr3;
    NSMutableArray *grouparr4;

    NSInteger heightCell;
    NSInteger number;
    
    UITableView *_cellTableView;
    NSMutableDictionary *diccell;//存对应的数据
    NSMutableArray *selectedArrcell;//二级列表是否展开状态
    NSMutableArray *titleDataArraycell;
    NSArray *dataArraycell;//数据源，显示每个cell的数据
    
    NSString *string0;
    NSString *string1;
    NSString *string2;
    NSString *string3;
    NSString *string4;
    NSString *string4Id;
    NSString *calculateArea;
    NSString *discountPrice;
    NSString *discountTotalPrice;
    NSString *discountAmount;
    NSString *discountRate;
    NSString *floorType;        //方案类别

}


@property (nonatomic, strong) UIButton *bcButton;

@property (nonatomic, strong) NSMutableArray *arr1;
@property (nonatomic, strong) NSMutableArray *arr2;
@property (nonatomic, strong) NSMutableArray *arr3;
@property (nonatomic, strong) NSMutableArray *arr4;
@property (nonatomic, strong) NSMutableArray *arr4Id;
@property (nonatomic, strong) NSMutableArray *arr1Id;
@property (nonatomic, strong) NSMutableArray *arr2Id;
@property (nonatomic, strong) NSMutableArray *arr3Id;

@property (nonatomic, strong) NSMutableArray *roomDataArr;
@end

@implementation HousingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatNavigationController];
    [self creatInitWithButtonsShowUI];
    _roomDataArr = [[NSMutableArray alloc] init];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    _arr1 = [[NSMutableArray alloc] init];
    _arr2 = [[NSMutableArray alloc] init];
    _arr3 = [[NSMutableArray alloc] init];
    _arr4 = [[NSMutableArray alloc] init];
    _arr4Id = [[NSMutableArray alloc] init];
    _arr1Id = [[NSMutableArray alloc] init];
    _arr2Id = [[NSMutableArray alloc] init];
    _arr3Id = [[NSMutableArray alloc] init];
    [self postGetCustomerDetailApi];
    
    dic = [[NSMutableDictionary alloc] init];
    selectedArr = [[NSMutableArray alloc] init];
    dataArray = [[NSArray alloc] init];
    
    diccell = [[NSMutableDictionary alloc] init];
    selectedArrcell = [[NSMutableArray alloc] init];
    dataArraycell = [[NSArray alloc] init];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH,EMM_HEIGHT-70-SafeAreaTopHeight) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsVerticalScrollIndicator = NO;
    //不要分割线
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    heightCell = 0;
    number = 1;
    [self initDataSource];
}

#pragma mark - api
- (void)postGetCustomerDetailApi {
    [_arr1 removeAllObjects];
    [_arr1Id removeAllObjects];
//    [self showHudInWindow:nil];
    GetPremisesListApi *api = [[GetPremisesListApi alloc] initWith];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetPremisesListApi *result = (GetPremisesListApi *)request;
        if (result.isSuccess) {
            GetPremisesList *get = result.resultData;
            for (PremisesList *list in get.premisesList) {
                [_arr1 addObject:list.premisesName];
                [_arr1Id addObject:list.premisesId];
            }
            if (get.premisesList.count > 0) {
                [dic setValue:_arr1 forKey:@"1"];
                [selectedArr addObject:[NSString stringWithFormat:@"1"]];
            }else {
                string1 = @"无";
                [self postGetBuildingListApiPremisesId:@""];
            }
            [_tableView reloadData];
        } else {
//            [self showToast:result.resultData.errorMsg];
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            NSString *projectCode = [userdf objectForKey:@"projectCode"];
            if ([NSString isStringEmpty2:projectCode] == NO) {
                [self showToast:result.resultData.errorMsg];
            }
            
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                [appInstance showLogin];
                
            } else if ( [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

#pragma mark - api
- (void)postGetBuildingListApiPremisesId:(NSString *)premisesId {
    [_arr2 removeAllObjects];
    [_arr2Id removeAllObjects];
//    [self showHudInWindow:nil];
    GetBuildingListApi *api = [[GetBuildingListApi alloc] initWithPremisesId:premisesId];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetBuildingListApi *result = (GetBuildingListApi *)request;
        if (result.isSuccess) {
            GetBuildingList *get = result.resultData;
            for (BuildingList *list in get.buildingList) {
                [_arr2 addObject:list.buildingName];
                [_arr2Id addObject:list.buildingId];
            }
            if (get.buildingList.count > 0) {
                [dic setValue:_arr2 forKey:@"2"];
                [selectedArr addObject:[NSString stringWithFormat:@"2"]];
            }else {
                string2 = @"无";
                [self postGetUnitListApiBuildingId:nil premisesId:premisesId];
            }
            [_tableView reloadData];
        } else {
            [self showToast:result.resultData.errorMsg];
        }
        
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

#pragma mark - api
- (void)postGetUnitListApiBuildingId:(NSString *)buildingId premisesId:(NSString *)premisesId {
    [_arr3 removeAllObjects];
    [_arr3Id removeAllObjects];
    
//    [self showHudInWindow:nil];
    GetUnitListApi *api = [[GetUnitListApi alloc] initWithBuildingId:buildingId premisesId:premisesId];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetUnitListApi *result = (GetUnitListApi *)request;
        if (result.isSuccess) {
            GetUnitList *get = result.resultData;
            for (UnitList *list in get.unitList) {
                [_arr3 addObject:list.unitName];
                [_arr3Id addObject:list.unitId];
            }
            if (get.unitList.count > 0) {
                [dic setValue:_arr3 forKey:@"3"];
                [selectedArr addObject:[NSString stringWithFormat:@"3"]];
            }else {
                string3 = @"无";
                [self postGetRoomListApiUnitId:nil buildingId:buildingId premisesId:premisesId];
            }
            [_tableView reloadData];
        } else {
            [self showToast:result.resultData.errorMsg];
        }
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

#pragma mark - api
- (void)postGetRoomListApiUnitId:(NSString *)unitId
                      buildingId:(NSString *)buildingId
                      premisesId:(NSString *)premisesId {
    [_arr4 removeAllObjects];
    [_arr4Id removeAllObjects];
//    [self showHudInWindow:nil];
    GetRoomListApi *api = [[GetRoomListApi alloc] initWithUnitId:unitId buildingId:buildingId premisesId:premisesId];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetRoomListApi *result = (GetRoomListApi *)request;
        if (result.isSuccess) {
            GetRoomList *get = result.resultData;
            for (RoomList *list in get.roomList) {
                [_arr4 addObject:list.roomName];
                [_arr4Id addObject:list];
            }
            if (_arr4.count == 0) {
                [self showToast:@"暂无房号可选！"];
            }
             [dic setValue:_arr4 forKey:@"4"];
             [selectedArr addObject:[NSString stringWithFormat:@"4"]];
            [_tableView reloadData];
        } else {
            [self showToast:result.resultData.errorMsg];
        }
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

#pragma mark - 导航

- (void)creatNavigationController {
    [self updateNavBar];
    self.navigationItem.title = @"意向房源";
    [self configLeftBtn];
}


- (void)creatInitWithButtonsShowUI {
    _bcButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _bcButton.frame = CGRectMake(15, EMM_HEIGHT-70-SafeAreaTopHeight, EMM_WIDTH-30, 50);
    [_bcButton setTitle:@"确定" forState:UIControlStateNormal];
    _bcButton.layer.masksToBounds = YES;
    _bcButton.layer.cornerRadius = 5;
    _bcButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [_bcButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _bcButton.backgroundColor = [UIColor colorFromHexCode:@"#ff7200"];
    [_bcButton addTarget:self action:@selector(bcButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_bcButton];
}

- (void)bcButtonClick:(UIButton *)btn {
  
    if (_housingNewBlock) {
      
        NSString *str1;
        if ([string1 isEqualToString:@"无"]) {
            str1 = @"";
        }else {
            str1 = string1;
        }
        NSString *str2;
        if ([string2 isEqualToString:@"无"]) {
             str2 = @"";
        }else {
            str2 = string2;
        }
        NSString *str3;
        if ([string3 isEqualToString:@"无"]) {
             str3 = @"";
        }else {
            str3 = string3;
        }
        if ([NSString isStringEmpty2:string4] == NO) {
            if ([string4 isEqualToString:@"选择房号"]) {
                [self showToast:@"房号未选择"];
                return;
            }
        }
        
        NSString *str = [NSString stringWithFormat:@"%@-%@-%@-%@-%@",string0,str1,str2,str3,string4];
//        _housingBlock(str, string4Id, calculateArea, discountPrice, discountTotalPrice,discountAmount,discountRate,floorType);

        _housingNewBlock(_roomDataArr,str);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)initDataSource
{
    titleDataArraycell = [[NSMutableArray alloc] init];
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    NSString *projectName = [userdf objectForKey:@"projectName"];
    string0 = projectName;
    string1 = @"选择组团";
    string2 = @"选择楼栋";
    string3 = @"选择单元";
    string4 = @"选择房号";
    
    titleDataArray = [[NSMutableArray alloc] initWithObjects:string0, string1,string2,string3,string4, nil];
    grouparr0 = [[NSMutableArray alloc]init];
    
    [dic setValue:grouparr0 forKey:@"0"];
}

#pragma mark----tableViewDelegate
//返回几个表头
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

//每一个表头下返回几行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *string = [NSString stringWithFormat:@"%ld",section];
    if ([selectedArr containsObject:string]) {
        NSArray *array1 = dic[string];
        return array1.count;
    }
    return 0;
}

//设置表头的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

//Section Footer的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 5)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

//设置view，将替代titleForHeaderInSection方法
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 50)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, tableView.frame.size.width-20, 20)];
    [view addSubview:titleLabel];
    UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 49.5, EMM_WIDTH, 0.5)];
    lineImage.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, EMM_WIDTH, 50);
    button.tag = 100+section;
    [button addTarget:self action:@selector(doButton:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    view.backgroundColor = [UIColor colorFromHexCode:@"#fff5e9"];
    UILabel *sLabel6 = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 2, 30)];
    sLabel6.backgroundColor = [UIColor colorFromHexCode:@"#ff7200"];
    [view addSubview:sLabel6];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(EMM_WIDTH-30, 15, 20, 20)];
    [view addSubview:imageView];
    if (section == 0) {
        titleLabel.text = string0;
    }else if (section == 1) {
        titleLabel.text = string1;
    }else if (section == 2) {
        titleLabel.text = string2;
    }else if (section == 3) {
        titleLabel.text = string3;
    }else if (section == 4) {
        titleLabel.text = string4;
    }
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *indexStr = [NSString stringWithFormat:@"%ld",indexPath.section];
    NSLog(@"%@",indexStr);
    static NSString *CellIdentifier = @"NewCustomersCell";
    NewCustomersCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"NewCustomersCell" owner:self options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 49.5, EMM_WIDTH, 0.5)];
    lineImage.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
    [cell addSubview:lineImage];
    cell.customLabel.hidden = YES;
    cell.qjImageView.hidden = YES;
    if ([selectedArr containsObject:indexStr]) {
        
        cell.nameLbael.text = dic[indexStr][indexPath.row];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *indexStr = [NSString stringWithFormat:@"%ld",indexPath.section];
    if ([selectedArr containsObject:indexStr]) {
        [selectedArr removeObject:indexStr];
        
        [selectedArr addObject:[NSString stringWithFormat:@"%d",[indexStr intValue]+1]];
    }
    if ([indexStr isEqualToString:@"1"]) {
        string1 = dic[indexStr][indexPath.row];
        NSString *strinId = [_arr1Id objectAtIndex:indexPath.row];
        [self postGetBuildingListApiPremisesId:strinId];
        
    }else if ([indexStr isEqualToString:@"2"]) {
        string2 = dic[indexStr][indexPath.row];
        NSString *strinId = [_arr2Id objectAtIndex:indexPath.row];
        [self postGetUnitListApiBuildingId:strinId premisesId:nil];
    }else if ([indexStr isEqualToString:@"3"]) {
        string3 = dic[indexStr][indexPath.row];
        NSString *strinId = [_arr3Id objectAtIndex:indexPath.row];
        [self postGetRoomListApiUnitId:strinId buildingId:nil premisesId:nil];
    }else if ([indexStr isEqualToString:@"4"]) {
        string4 = dic[indexStr][indexPath.row];
        RoomList *list = [_arr4Id objectAtIndex:indexPath.row];
        string4Id = list.roomId;
        calculateArea = list.calculateArea;
        discountPrice = list.discountPrice;
        discountTotalPrice = list.discountTotalPrice;
        discountAmount = list.discountAmount;
        floorType = list.floorType;
        if ([list.floorType isEqualToString:@"0"]) {
            discountRate = list.discountRate;
        }else {
            discountRate = [NSString stringWithFormat:@"%.2f",[list.discountRate floatValue]*100];
            list.discountRate = [NSString stringWithFormat:@"%.2f",[list.discountRate floatValue]*100];
        }
        [_roomDataArr addObject:list];
    }
    [_tableView reloadData];
}

-(void)doButton:(UIButton *)sender {
    NSString *string = [NSString stringWithFormat:@"%ld",sender.tag-100];
    //数组selectedArr里面存的数据和表头想对应，方便以后做比较
    if ([selectedArr containsObject:string]) {
        [selectedArr removeObject:string];
    }else {
        [selectedArr addObject:string];
    }
    [_tableView reloadData];
    
}


@end
